<template>
  <!-- 搜索工作栏 -->
  <el-form
    class="-mb-15px my-form"
    :model="queryParams"
    ref="queryFormRef"
    :inline="true"
    label-width="60px"
  >
    <template v-for="(item, index) in filterInfo" :key="index">
      <el-form-item v-if="item.value == 'Type'" :label="item.label">
        <el-select
          v-model="queryParams.type"
          filterable
          clearable
          placeholder="请选择"
          style="width: 160px"
          @change="changeType"
        >
          <el-option
            v-for="item in typeList"
            :key="item.Label"
            :label="item.Label"
            :value="item.Value"
          />
        </el-select>
      </el-form-item>
      <el-form-item v-if="item.value == 'Key'" :label="item.label">
        <el-select
          v-model="queryParams.key"
          filterable
          clearable
          placeholder="请选择"
          style="width: 160px"
          @change="changeKey"
        >
          <el-option
            v-for="item in keyList"
            :key="item.Label"
            :label="item.Label"
            :value="item.Value"
          />
        </el-select>
      </el-form-item>
      <el-form-item v-if="item.value == 'Date'" :label="item.label">
        <el-date-picker
          v-if="item.type == 'Date'"
          ref="date"
          v-model="queryParams.date"
          placeholder="请输入"
          type="date"
          value-format="YYYY-MM-DD"
        />
        <el-date-picker
          v-if="item.type == 'DateRange'"
          ref="dateRange"
          v-model="queryParams.date"
          placeholder="请输入"
          type="daterange"
          value-format="YYYY-MM-DD"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
        <el-date-picker
          v-if="item.type == 'DateTimeRange'"
          ref="dateTimeRange"
          v-model="queryParams.date"
          placeholder="请输入"
          type="datetimerange"
          value-format="YYYY-MM-DD HH:mm:ss"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
      </el-form-item>
    </template>
    <el-form-item>
      <template v-for="(item, index) in buttonInfo" :key="index">
        <el-button type="primary" :icon="Search" v-if="item.value == 'Search'" @click="handleQuery">
          {{ item.label }}</el-button
        >
        <el-button v-if="item.value == 'Reset'" :icon="Refresh" @click="handleReset">
          {{ item.label }}</el-button
        >
        <el-button
          type="success"
          :icon="Select"
          v-if="item.value == 'POReceive'"
          @click="$emit('handlePush', queryParams)"
        >
          {{ item.label }}</el-button
        >
        <template v-if="item.value == 'Export'">
          <ExportButton :label="item.label" :partParams="basicParams" />
        </template>
        <el-button
          v-if="item.value == 'Add'"
          class="btn-add"
          type="success"
          :icon="Plus"
          plain
          @click="handleAdd"
          >{{ item.label }}
        </el-button>
        <el-button
          v-if="item.value == 'Upload'"
          class="btn-add"
          type="warning"
          :icon="Upload"
          plain
        >
          {{ item.label }}
        </el-button>
      </template>
    </el-form-item>
  </el-form>
  <div class="flex justify-between">
    <div class="filter-box">
      <div
        v-if="queryParams.keyType == 'Select'"
        class="content border"
        style="height: calc(100vh - 180px)"
      >
        <el-checkbox
          class="pt-2 mb-2"
          v-model="checkAll"
          :indeterminate="isIndeterminate"
          @change="handleCheckAllChange"
        >
          全选
        </el-checkbox>
        <hr />
        <el-checkbox-group class="mt-2" v-model="checkedValues" @change="handleCheckedChange">
          <el-checkbox v-for="item in valueList" :key="item.Value" :label="item.Value">
            {{ item.Label }} </el-checkbox
          ><br />
        </el-checkbox-group>
      </div>
      <el-input
        v-else
        style="width: 100%"
        type="textarea"
        :rows="30"
        v-model="queryParams.value"
        placeholder="请输入"
        clearable
      />
    </div>
    <div class="table-box">
      <!-- 列表 -->
      <MyTable ref="table" :partParams="tableParams" :table-info="tableInfo" />
    </div>
  </div>

  <!-- 新增弹框 -->
  <AddModal ref="modalRef" :partParams="basicParams" @refresh="refresh" />
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, defineProps } from 'vue'
import ExportButton from '../common/ExportButton.vue'
import * as BasicApi from '@/api'
import { objectToQueryParams } from '@/utils/objectToQuery'
import { Plus, Select, Search, Refresh, Upload } from '@element-plus/icons-vue'

import MyTable from './component/MyTable.vue'
import AddModal from '../common/AddModal.vue'
import { useMessage } from '@/hooks/useMessage'

//定义接收的props
const props = defineProps({
  // 定义一个对象类型的 prop
  data: {
    type: Object,
    default: () => ({ groupName: '', jobType: '' })
  }
})

const formQuery = {
  type: '',
  key: '',
  keyType: 'text',
  value: '',
  date: '',
  pageNo: 1,
  pageSize: 15
}
const queryParams = reactive({
  type: '',
  key: '',
  keyType: 'text',
  value: '',
  date: '',
  pageNo: 1,
  pageSize: 15
})

const emit = defineEmits(['getData', 'getColumnData', 'handlePush', 'openModal'])

//日期控件
const date = ref()
const dateRange = ref()
const dateTimeRange = ref()
import type { CheckboxValueType } from 'element-plus'

const checkAll = ref(false)
const isIndeterminate = ref(true)
const checkedValues = ref<any[]>([])

const handleCheckAllChange = (val: CheckboxValueType) => {
  //筛选出所有的value
  const arr = valueList.value.map((item) => item.Value)
  checkedValues.value = val ? arr : []
  isIndeterminate.value = false
}
const handleCheckedChange = (value: CheckboxValueType[]) => {
  const checkedCount = value.length
  checkAll.value = checkedCount === valueList.value.length
  isIndeterminate.value = checkedCount > 0 && checkedCount < valueList.value.length
}

//查询
function handleQuery() {
  //去除输入框内的空格
  queryParams.value = queryParams.value.trim()
  const temp = JSON.parse(JSON.stringify(queryParams))
  const post = {
    ...temp,
    ...basicParams,
    operType: 'GetList'
  }
  //处理日期
  if (dateRange.value || dateTimeRange.value) {
    const startDateStr = queryParams.date[0]
    const endDateStr = queryParams.date[1]
    post.startDate = startDateStr
    post.endDate = endDateStr
    delete post.date
  }
  if (checkedValues.value.length) {
    jsonData.value = checkedValues.value.map((item) => {
      return { value: item }
    })
  } else {
    jsonData.value = []
  }
  // getData({inputStr: post, jsonData: jsonData.value})
  tableParams.value = { inputStr: post, jsonData: jsonData.value }
}

//重置
function handleReset() {
  //将表单置空
  Object.assign(queryParams, formQuery)
  //清空值的下拉框数据
  valueList.value = []
}

//获取类型
const typeList = ref<any[]>([])
const getTypeList = async () => {
  const params = {
    ...basicParams,
    operType: 'GetType'
  }
  const inputStr = objectToQueryParams(params)
  const result = (await BasicApi.Query({ inputStr })) as any
  const { code, msg, data } = result
  if (code !== 200) {
    message.error(msg)
    return
  }
  typeList.value = data.listInfo || []
}

//获取条件
const keyList = ref<any[]>([])
const getKeyList = async () => {
  const params = {
    ...basicParams,
    type: queryParams.type,
    operType: 'GetKey'
  }
  const inputStr = objectToQueryParams(params)
  const result = (await BasicApi.Query({ inputStr })) as any
  const { code, msg, data } = result
  if (code !== 200) {
    message.error(msg)
    return
  }
  keyList.value = data.listInfo || []
}

function changeType() {
  queryParams.key = ''
  keyList.value = []
  queryParams.keyType = ''
  queryParams.value = ''
  valueList.value = []
  checkedValues.value = []
  if (!queryParams.type) {
    return
  }
  getKeyList()
}

function changeKey() {
  queryParams.value = ''
  checkAll.value = false
  checkedValues.value = []
  if (!queryParams.key) {
    return
  }
  //先获取Key的Type
  const result = keyList.value.filter((item) => item.Value === queryParams.key)
  queryParams.keyType = (result.length && result[0].ValueType) || 'text'
  //如果Type为select则要去获取下拉框数据
  if (queryParams.keyType == 'Select') {
    getValueList()
  }
}

//获取值
const valueList = ref<any[]>([])
const getValueList = async () => {
  const post = {
    ...basicParams,
    type: queryParams.type,
    key: queryParams.key,
    operType: 'GetValue'
  }
  const inputStr = objectToQueryParams(post)
  const result = (await BasicApi.Query({ inputStr })) as any
  const { code, msg, data } = result
  if (code !== 200) {
    message.error(msg)
    return
  }
  valueList.value = data.listInfo || []
}

const tableInfo = ref()
//是否有类型
const isShowType = ref(false)
//获取筛选项
const filterInfo = ref<any[]>([]) // 列表的数据
const buttonInfo = ref<any[]>([])
const getFilter = async () => {
  const post = {
    ...basicParams,
    operType: 'GetPageInfo'
  }
  const inputStr = objectToQueryParams(post)
  const result = (await BasicApi.Query({ inputStr, jsonData: '' })) as any
  const { code, msg, data } = result
  if (code !== 200) {
    message.error(msg)
    return
  }
  const { filter, operate } = data.pageInfo
  filterInfo.value = filter.filter((item: any) => item.type !== 'Button')
  const tempInfo = filter.filter((item: any) => item.type === 'Button')
  buttonInfo.value = tempInfo.concat(operate)
  const res = filter.filter((item: any) => item.value == 'Type')
  isShowType.value = res.length ? true : false
  //将表头信息和行操作传给table
  tableInfo.value = data
}

//新增
const modalRef = ref()
function handleAdd() {
  modalRef.value.open()
}

const basicParams = {
  groupName: props.data.groupName,
  jobType: props.data.jobType
}

const tableParams = ref()

const table = ref()
/** 查询列表 */
const getData = async (query: any) => {
  tableParams.value = JSON.parse(JSON.stringify(query))
}

const message = useMessage()

const jsonData = ref<any[]>([])
const refresh = () => {
  const inputStr = {
    ...basicParams,
    ...queryParams
  }
  const jsonData =
    (checkedValues.value.length &&
      checkedValues.value.map((item) => {
        return { value: item }
      })) ||
    []
  tableParams.value = { inputStr, jsonData }
  getValueList()
}

onMounted(async () => {
  await getFilter()
  isShowType.value ? getTypeList() : getKeyList()
})
</script>
<style lang="less" scoped>
.el-form--inline .el-form-item{
  margin-right: 15px;
}

:deep(.el-checkbox-group) {
  display: flex;
  flex-direction: column;
}
.filter-box {
  width: 220px;
}
.table-box {
  width: calc(100% - 235px);
}
.filter-box .content {
  padding: 0 10px;
}
</style>
